﻿using System;

namespace Borg
{
    public class ExtensionBase : MarshalByRefObject
    {
        private ExtensionContext _extensionContext;

        public ExtensionContext Context
        {
            get
            {
                if (_extensionContext == null)
                    throw new InvalidOperationException(
                        "The extension context has not been set." +
                        " This error occurs if a class derived from ExtensionBase is" +
                        " instantiated by the user and not by the Borg runtime." +
                        " Only Borg can set the extension context which is" +
                        " required by operations inherited from ExtensionBase");
                
                return _extensionContext;
            }
            internal set { _extensionContext = value; }
        }

        protected Plugin Plugin
        {
            get { return Context.Extension.ExtensionType.Plugin; }
        }

        protected ExtensionType ExtensionType
        {
            get { return Context.Extension.ExtensionType; }
        }

        protected Extension Extension
        {
            get { return Context.Extension; }
        }

        protected MetaElementCollection<Plug> Plugs
        {
            get { return Context.Extension.Plugs; }
        }

        protected MetaElementCollection<Slot> Slots
        {
            get { return Context.Extension.Slots; }
        }

        protected Runtime Runtime
        {
            get { return Plugin.runtime; }
        }

        protected ExtensionPersistor Persistor
        {
            get { return Context.Persistor; }
        }

        protected ExtensionLogger Logger
        {
            get { return Context.Logger; }
        }

        protected SettingDictionary Settings
        {
            get { return Context.Settings; }
            set { Context.Settings = value; }
        }

        public ExtensionBase()
        {
            Context = Activator.ActivationContext;
            Activator.ActivationContext = null;
            Extension.Deactivated += ExtensionDeactivated;
        }

        protected virtual void OnDeactivated(ExtensionEventArgs args)
        { }

        private void ExtensionDeactivated(ExtensionEventArgs args)
        {
            Extension.Deactivated -= ExtensionDeactivated;
            OnDeactivated(args);
        }
    }
}
